package com.example.sunmiv1.utils.zxing.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.ScanGoodInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.ScanGoodCallback;
import com.example.sunmiv1.utils.zxing.camera.CameraManager;
import com.example.sunmiv1.utils.zxing.decoding.CaptureActivityHandler;
import com.example.sunmiv1.utils.zxing.decoding.DecodeHandler;
import com.example.sunmiv1.utils.zxing.decoding.InactivityTimer;
import com.example.sunmiv1.utils.zxing.decoding.RGBLuminanceSource;
import com.example.sunmiv1.utils.zxing.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;


/**
 * Initial the camera
 *
 * @author Ryan.Tang
 */
public class CaptureActivity extends AppCompatActivity implements Callback {

    private static final int REQUEST_CODE_SCAN_GALLERY = 100;
    private static final String TAG = "TAG";

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private ImageView back;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private ProgressDialog mProgress;
    private String photo_path;
    private Bitmap scanBitmap;
    private TextView title;
    //	private Button cancelScanButton;
    /**
     * Called when the activity is first created.
     */

    private TextView allClassNum, allNum;

    private ACache aCache;
    private int scannerType = 0;//報損/盤點/採購/採購退貨/出庫    1/2/3/4/5

    private List<ScanGoodInfo.DataBean> list = new ArrayList<>();
    private LinearLayout linear_scanner;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_scanner);
        aCache = ACache.get(this);
        list.clear();
        scannerType = getIntent().getIntExtra("scannerType", 0);
        //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);
        CameraManager.init(getApplication());
        getSupportActionBar().hide();
        viewfinderView = findViewById(R.id.viewfinder_content);
        allClassNum = findViewById(R.id.scanner_allClassNum);
        allNum = findViewById(R.id.scanner_allNum);
        back = findViewById(R.id.title_back);
        linear_scanner = findViewById(R.id.linear_scanner);
        if (scannerType != 0) {
            linear_scanner.setVisibility(View.VISIBLE);
        } else {
            linear_scanner.setVisibility(View.GONE);
        }
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scannerType == 0) {
                    CaptureActivity.this.finish();
                } else {
                    Intent resultIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) list);
                    resultIntent.putExtras(bundle);
                    setResult(RESULT_OK, resultIntent);
                    finish();
                }
            }
        });
        title = findViewById(R.id.title_title);
        title.setText(R.string.barCode);
//		cancelScanButton = (Button) this.findViewById(R.id.btn_cancel_scan);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);


        if (scannerType != 0) {
            if (searchTimer == null) {
                Log.e(TAG, "onSuccess: 8251");
                searchTimer = new Timer();
            }
            searchTask = new SearchTimerTask();
            searchTimer.schedule(searchTask, 0, 3000);
        }

        //添加toolbar
//        addToolbar();
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SCAN_GALLERY:
                    //獲取選中圖片的路徑
                    Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
                    if (cursor.moveToFirst()) {
                        photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    }
                    cursor.close();

                    mProgress = new ProgressDialog(CaptureActivity.this);
                    mProgress.setMessage("正在掃描...");
                    mProgress.setCancelable(false);
                    mProgress.show();

                    new Thread(() -> {
                        Result result = scanningImage(photo_path);
                        if (result != null) {
                            if (scannerType != 0) {
                                String info = result.getText();
                                switch (scannerType) {
                                    case 1:
                                        lossScanCodeGoods(info);
                                        break;
                                    case 2:
                                        break;
                                    case 3:
                                        break;
                                    case 4:
                                        break;
                                    case 5:
                                        break;
                                    default:
                                        break;
                                }
                            } else {
                                Intent resultIntent = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putString(Constant.INTENT_EXTRA_KEY_QR_SCAN, result.getText());
                                resultIntent.putExtras(bundle);
                                CaptureActivity.this.setResult(RESULT_OK, resultIntent);
                            }
                        } else {
                            Message m = handler.obtainMessage();
                            m.what = R.id.decode_failed;
                            m.obj = "Scan failed!";
                            handler.sendMessage(m);
                        }
                    }).start();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 掃描二維碼圖片的方法
     *
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //設置二維碼內容的編碼

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先獲取原大小
        scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false; // 獲取新的大小
        int sampleSize = (int) (options.outHeight / (float) 200);
        if (sampleSize <= 0) {
            sampleSize = 1;
        }
        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);
        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {
            return reader.decode(bitmap1, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scanner_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
//        initBeepSound();
        vibrate = true;

        //quit the scan view
//		cancelScanButton.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				CaptureActivity.this.finish();
//			}
//		});
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }


    Handler mHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (handler != null) {
                try {
                    mHandler.postDelayed(runnable, 1000);
                    handler.restartPreviewAndDecode(); // 實現多次掃描
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private Timer searchTimer;
    private SearchTimerTask searchTask;


    private class SearchTimerTask extends TimerTask {
        @Override
        public void run() {
            try {
                handler.restartPreviewAndDecode(); // 實現多次掃描
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 攝像頭掃碼返回結果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {

    }

    /**
     * 報損掃描商品
     */
    private void lossScanCodeGoods(String info) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("search_info", info);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(this, Common.LOSS_SCAN_CODE_GOODS, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(CaptureActivity.this, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            ScanGoodInfo scanGoodInfo = GsonUtils.JsonToBean(text, ScanGoodInfo.class);
                            scanGoodInfo.getData().setLoss_num(1);
                            boolean flag = false;
                            int size = 0;
                            for (int i = 0; i < list.size(); i++) {
                                if (list.get(i).getId().equals(scanGoodInfo.getData().getId())) {
                                    flag = true;
                                    list.get(i).setLoss_num(list.get(i).getLoss_num() + 1);
                                }
                                size = (int) (size + list.get(i).getLoss_num());
                            }
                            if (!flag) {
                                size = size + 1;
                                list.add(scanGoodInfo.getData());
                            }
                            Log.e(TAG, "onSuccess: size=============" + size);
                            allClassNum.setText(list.size() + "");
                            allNum.setText(size + "");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {

            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet, viewfinderView, new ScanGoodCallback() {
                @Override
                public void success(Result result, Bitmap barcode) {
                    Log.e(TAG, "handleDecode: result==========" + result.getText());
                    inactivityTimer.onActivity();
                    playBeepSoundAndVibrate();
                    String resultString = result.getText();
                    if (TextUtils.isEmpty(resultString)) {
                        Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
                        CaptureActivity.this.finish();
                    } else {
                        if (scannerType != 0) {
                            switch (scannerType) {
                                case 1:
                                    lossScanCodeGoods(resultString);
                                    break;
                                case 2:
                                    break;
                                case 3:
                                    break;
                                case 4:
                                    break;
                                case 5:
                                    break;
                                default:
                                    break;
                            }
                        } else {
                            Intent resultIntent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putString(Constant.INTENT_EXTRA_KEY_QR_SCAN, resultString);
                            resultIntent.putExtras(bundle);
                            setResult(RESULT_OK, resultIntent);
                            CaptureActivity.this.finish();
                        }
                    }
                }
            });
            DecodeHandler.handler = handler;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

}
